package com.salesforce.samples.templateapp;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;
import com.salesforce.samples.templateapp.model.Bean_Class;
import com.salesforce.samples.templateapp.model.Contacts;

public class FragmentB  extends Fragment implements OnClickListener, OnItemClickListener{
	ScrollView svAccount,svContact;
	LinearLayout llayout;
	EditText etLookup,etAccountNumber,etAccountName,etParentAccount,etAnnuaLRevenue,etEmployees,etPhone,etfax,etwebsite,etBilingStreet,etBilingCity,etBilingState,etBilingZip,etBilingcountry,etShippingStreet,etShippingcity,etshippingstate,etShippingcode,etShippingCountry;
	EditText etMaillingCity,etMaillingStreet,etMailingCountry,etMaillingstate,etMaillingZip,etContactAccountName,etOtherCity,etOtherStreet,etOtherState,etOtherCountry,etOtherZip,etFirstName,etLastName,etTitle,etContactphone,etMobile,etEmail,etDescription;
	TextView tvAccountNumber,tvAccountName,tvParentAccount,tvAnnuaLRevenue,tvEmployees,tvPhone,tvfax,
	tvwebsite,tvBilingStreet,tvBilingCity,tvBilingState,tvBilingZip,tvBilingcountry,billingToShipping,tvContactBillingToShipping,tvRating,tvOwnership,tvType,tvIndustry,
	tvShippingStreet,tvShippingcity,tvshippingstate,tvShippingcode,tvShippingCountry,tvContactLastName;
	RestClient client;
	TextView mName,mAccountNumber,mPhone,mDescrption,mWebsite;
	Button mSave,mNewContact,mEdit,mContactSave;
	Spinner mType,mIndustry,mRating,mOwnerShip,etLeadSource;
	Bean_Class bean;
	ListView lvLookup;
	
	ArrayList<Bean_Class> filterList;
	boolean isFiltered;
	ArrayList<Bean_Class> data;
	Dialog lookupDialog;
	String parantAccountID;
	static ArrayList<Contacts> contactList;
	boolean flag;
	GlobalListener mHomeItemListener;   
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Intent launchingIntent = getActivity().getIntent();
		String color = launchingIntent.getStringExtra("COLOR_TYPE");
		View viewer = (View) inflater.inflate(R.layout.account_page, container, false);
		return viewer;
		}

	
	
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		mHomeItemListener = (GlobalListener) (activity);
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		
		
		svAccount = (ScrollView) getView().findViewById(R.id.accountScrooview);
		svContact = (ScrollView) getView().findViewById(R.id.contactScrooview);
		llayout = (LinearLayout) getView().findViewById(R.id.llDisplayLayout);
		mName  = (TextView) getView().findViewById(R.id.tvAccountName);
		mAccountNumber  = (TextView) getView().findViewById(R.id.tvAccountNumber);
		mPhone  = (TextView) getView().findViewById(R.id.tvPhone);
		mWebsite  = (TextView) getView().findViewById(R.id.tvWebSite);
		tvAnnuaLRevenue  = (TextView) getView().findViewById(R.id.tvAnnualRevenue);
		tvEmployees  = (TextView) getView().findViewById(R.id.tvEmpoyees);
		tvfax  = (TextView) getView().findViewById(R.id.tvFax);
		tvBilingStreet  = (TextView) getView().findViewById(R.id.tvBillingStreet);
		tvBilingCity  = (TextView) getView().findViewById(R.id.tvBillingCity);
		tvBilingState  = (TextView) getView().findViewById(R.id.tvBillingState);
		tvBilingZip  = (TextView) getView().findViewById(R.id.tvBillingCode);
		tvBilingcountry  = (TextView) getView().findViewById(R.id.tvBillingCountry);
		tvShippingStreet  = (TextView) getView().findViewById(R.id.tvShippingStreet);
		tvShippingcity  = (TextView) getView().findViewById(R.id.tvShippingCity);
		tvshippingstate  = (TextView) getView().findViewById(R.id.tvShippingState);
		tvShippingcode  = (TextView) getView().findViewById(R.id.tvShippingCode);
		tvShippingCountry  = (TextView) getView().findViewById(R.id.tvShippingCountry);
		tvRating = (TextView)getView().findViewById(R.id.tvRating);
		tvOwnership = (TextView)getView().findViewById(R.id.tvOwnership);
		tvIndustry = (TextView)getView().findViewById(R.id.tvIndustry);
		tvType = (TextView)getView().findViewById(R.id.tvType);
		mWebsite  = (TextView) getView().findViewById(R.id.tvWebSite);
		mSave = (Button) getView().findViewById(R.id.btSave1);
		mNewContact = (Button) getView().findViewById(R.id.btNewContact);
		mEdit = (Button) getView().findViewById(R.id.btEdit);
		mContactSave = (Button) getView().findViewById(R.id.btSave2);
		mType = (Spinner) getView().findViewById(R.id.etType);
		mRating = (Spinner) getView().findViewById(R.id.etRating);
		mIndustry = (Spinner) getView().findViewById(R.id.etIndustry);
		mOwnerShip = (Spinner) getView().findViewById(R.id.etOwnership);
		billingToShipping = (TextView)getView().findViewById(R.id.tvBillingToShipping);
		tvContactBillingToShipping = (TextView)getView().findViewById(R.id.tvContactBillingToShipping);
		
		mContactSave.setOnClickListener(this);              
		tvContactBillingToShipping.setOnClickListener(this);
		billingToShipping.setOnClickListener(this);
		mSave.setOnClickListener(this);
		mNewContact.setOnClickListener(this);
		mEdit.setOnClickListener(this);
		
		etAccountNumber  = (EditText) getView().findViewById(R.id.etAccountNumber);
		etAccountName  = (EditText) getView().findViewById(R.id.etAccountName);
		etAnnuaLRevenue  = (EditText) getView().findViewById(R.id.etAnnualRevenue);
		etBilingCity  = (EditText) getView().findViewById(R.id.etBillingCity);
		etBilingcountry  = (EditText) getView().findViewById(R.id.etBillingCountry);
		etBilingState  = (EditText) getView().findViewById(R.id.etBillingState);
		etBilingStreet  = (EditText) getView().findViewById(R.id.etBillingStreet);
		etBilingZip  = (EditText) getView().findViewById(R.id.etBillingCode);
		etEmployees  = (EditText) getView().findViewById(R.id.etEmpoyees);
		etfax  = (EditText) getView().findViewById(R.id.etFax);
		etParentAccount  = (EditText) getView().findViewById(R.id.etParentAccount);
		etParentAccount.setOnClickListener(this);
		etPhone  = (EditText) getView().findViewById(R.id.etPhone);
		etShippingcity  = (EditText) getView().findViewById(R.id.etShippingCity);
		etShippingcode  = (EditText) getView().findViewById(R.id.etShippingCode);
		etShippingCountry  = (EditText) getView().findViewById(R.id.etShippingCountry);
		etshippingstate  = (EditText) getView().findViewById(R.id.etShippingState);
		etShippingStreet  = (EditText) getView().findViewById(R.id.etShippingStreet);
		etwebsite  = (EditText) getView().findViewById(R.id.etWebSite);
		
		
		etMailingCountry = (EditText) getView().findViewById(R.id.etMailingcountry);
		etMaillingCity = (EditText) getView().findViewById(R.id.etMailingcity);
		etMaillingstate = (EditText) getView().findViewById(R.id.etMailingState);
		etMaillingStreet = (EditText) getView().findViewById(R.id.etMailingStreet);
		etMaillingZip = (EditText) getView().findViewById(R.id.etMailingcode);
		etContactAccountName = (EditText) getView().findViewById(R.id.etContactAccountName);
		etOtherCity = (EditText) getView().findViewById(R.id.etOtherCity);
		etOtherCountry = (EditText) getView().findViewById(R.id.etOthercountry);
		etOtherState = (EditText) getView().findViewById(R.id.etOtherState);
		etOtherStreet = (EditText) getView().findViewById(R.id.etOtherstreet);
		etOtherZip = (EditText) getView().findViewById(R.id.etOthercode);
		etFirstName = (EditText) getView().findViewById(R.id.etFirstname);
		etLastName = (EditText) getView().findViewById(R.id.etLastname);
		etTitle = (EditText) getView().findViewById(R.id.etTite);
		etMobile = (EditText) getView().findViewById(R.id.etMobile);
		etEmail = (EditText) getView().findViewById(R.id.etEmail);
		etContactphone = (EditText) getView().findViewById(R.id.etContactPhone);
		etLeadSource = (Spinner) getView().findViewById(R.id.etLeadSource);
		etDescription = (EditText) getView().findViewById(R.id.etDescription);
				
		
		tvContactLastName = (TextView) getView().findViewById(R.id.tvContactLastName);
		client = MainActivity.mActivity.client;
	}
	/**
	* for updating the color from the given input
	* @param color
	*/
	
	public void editAcount() {

		etAccountName.setText(bean.getName());
		etfax.setText(bean.getFax());
		etAnnuaLRevenue.setText(bean.getAnnualRevenue());
		etEmployees.setText(bean.getNumberOfEmployees());
		etAccountNumber.setText(bean.getAccountNumber());
		etPhone.setText(bean.getPhno());
		etwebsite.setText(bean.getWebsite());
		etBilingCity.setText(bean.getBillingCity());
		etBilingcountry.setText(bean.getBillingCountry());
		etBilingState.setText(bean.getBillingState());
		etBilingStreet.setText(bean.getBillingStreet());
		etBilingZip.setText(bean.getBillingPostalCode());
		etShippingcity.setText(bean.getShippingCity());
		etShippingCountry.setText(bean.getShippingCountry());
		etshippingstate.setText(bean.getShippingState());
		etShippingcode.setText(bean.getShippingPostalCode());
		etShippingStreet.setText(bean.getShippingStreet());
		parantAccountID = bean.getId();
		Log.i("NCS", "Update id 1 :" + bean.getId());
	}

	public void updateAccount(String id){
	
	String objectType = "Account";
	HashMap<String, Object> fields = new HashMap<String, Object>();
	fields.put("Name",etAccountName.getText().toString());
	fields.put("AccountNumber",etAccountNumber.getText().toString());
	fields.put("AnnualRevenue",etAnnuaLRevenue.getText().toString());
	fields.put("Fax",etfax.getText().toString());
	fields.put("Phone",etPhone.getText().toString());
	fields.put("Website",etwebsite.getText().toString());
	fields.put("NumberOfEmployees",etEmployees.getText().toString());
	fields.put("Industry", mIndustry.getSelectedItem().toString());
	fields.put("Ownership", mOwnerShip.getSelectedItem().toString());
	fields.put("Type", mType.getSelectedItem().toString());
	fields.put("Rating", mRating.getSelectedItem().toString());
	//fields.put("ParentId",parantAccountID);
	fields.put("BillingCity",etBilingCity.getText().toString());
	fields.put("BillingCountry",etBilingcountry.getText().toString());
	fields.put("BillingPostalCode",etBilingZip.getText().toString());
	fields.put("BillingState",etBilingState.getText().toString());
	fields.put("BillingStreet",etBilingStreet.getText().toString());
	fields.put("ShippingCity",etShippingcity.getText().toString());
	fields.put("ShippingCountry",etShippingCountry.getText().toString());
	fields.put("ShippingPostalCode",etShippingcode.getText().toString());
	fields.put("ShippingState",etshippingstate.getText().toString());
	fields.put("ShippingStreet",etShippingStreet.getText().toString());
	
	try {
	    RestRequest restRequest = RestRequest.getRequestForUpdate(Bean_Class.api_Version,objectType,id,fields);
	    
	    Log.i("NCS","REquest is  :"+restRequest);
	    
	    client.sendAsync(restRequest, new AsyncRequestCallback() {
			@Override
			public void onSuccess(RestRequest request, RestResponse result) {
				try {     
					Log.i("TPT","Response is   :"+result);
					mHomeItemListener.onCategoryClicked(-2);
					JSONObject json = new JSONObject(result.toString());
					if(json!= null){
						Log.i("TPT","Response is   :"+json.getString("success"));
						if(json.getString("success").equalsIgnoreCase("true")){
							
							etAccountNumber.setText("");
							etAccountName.setText("");
							etAnnuaLRevenue.setText("");
							etBilingCity.setText("");
							etBilingcountry.setText("");
							etBilingState.setText("");
							etBilingStreet.setText("");
							etBilingZip.setText("");
							etEmployees.setText("");
							etfax.setText("");
							etParentAccount.setText("");
							etPhone .setText("");
							etShippingcity.setText("");
							etShippingcode.setText("");
							etShippingCountry.setText("");
							etshippingstate.setText("");
							etShippingStreet.setText("");
							etwebsite.setText("");
						
						}
						
					}
					
					
					}                                
				catch (Exception e) {
					Log.i("TPT","Exception is   :"+e.getMessage());                      
				}
			}
			
			//@Override
			public void onError(Exception exception) {
				EventsObservable.get().notifyEvent(EventType.RenditionComplete);
			}
		});
	} 
	catch (Exception e) {
		Log.i("NCS","Exception is   :"+e.getMessage());
	    
	}

}
	public void updateColor(int position)
	{
		bean = FragmentA.list.get(position);
		mName.setText(bean.getName());
		tvfax.setText(bean.getFax());
		tvAnnuaLRevenue.setText(bean.getAnnualRevenue());
		tvEmployees.setText(bean.getNumberOfEmployees());
		mAccountNumber.setText(bean.getAccountNumber());
		mPhone.setText(bean.getPhno());                 
		mWebsite.setText(bean.getWebsite());
		tvBilingCity.setText(bean.getBillingCity());
		tvBilingcountry.setText(bean.getBillingCountry());
		tvBilingState.setText(bean.getBillingState());
		tvBilingStreet.setText(bean.getBillingStreet());
		tvBilingZip.setText(bean.getBillingPostalCode());
		tvShippingcity.setText(bean.getShippingCity());
		tvShippingCountry.setText(bean.getShippingCountry());
		tvshippingstate.setText(bean.getShippingState());
		tvShippingcode.setText(bean.getShippingPostalCode());
		tvShippingStreet.setText(bean.getShippingStreet());
		
		tvRating.setText(bean.getRating());
		tvOwnership.setText(bean.getOwnership());
		tvIndustry.setText(bean.getIndustry());
		tvType.setText(bean.getType());
		
		             
		getContacts(bean.getId());
		
	}


	public void getContacts(String id){

		try{
		//String accounts = "Select Name,AccountNumber,Phone,Description,Website from Account";
//		String accounts = "Select Id,Name,AccountNumber,AnnualRevenue,Fax,Phone,NumberOfEmployees,Ownership,Type,Industry,BillingCity,BillingState,BillingStreet,ShippingCity,ShippingCountry,ShippingPostalCode,ShippingState,ShippingStreet,BillingCountry,BillingPostalCode,Rating,Description,Website from Account";
       
        String accounts = "Select LastName,FirstName,AccountId,Title,Phone,MobilePhone,Email,MailingStreet,MailingCity,MailingState,MailingCountry,MailingPostalCode,OtherStreet,OtherCity,OtherState,OtherPostalCode,OtherCountry from Contact where AccountId ="+"'"+id+"'";
        Log.i("TPT","SOQL is     :"+accounts);
		RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

		client.sendAsync(restRequest, new AsyncRequestCallback() {
			@Override
			public void onSuccess(RestRequest request, RestResponse result) {
				try {            
					Log.i("TPT","Contact is   :"+result);
		            
							JSONObject jsonObject1 = new JSONObject(result.asString());
							Log.i("NCS","jsonobject1  is  :"+jsonObject1.length());
							
							JSONArray jsonArray = jsonObject1.getJSONArray("records");
							Log.i("RGT","jsonArray  is  :"+jsonArray.length());
							
							contactList = new ArrayList<Contacts>();
							Gson _gson = new Gson();
							for(int i=0; i< jsonArray.length(); i++)
							{
								if(!jsonArray.isNull(i)){
						 	   		Contacts bean = _gson.fromJson(jsonArray.getString(i), Contacts.class);
						 	   	contactList.add(bean);
						 	   		}
							}
							
							
							
						if(contactList.size()>0){
							for(Contacts bean : contactList){
							tvContactLastName.setText(bean.getLastName());
							}
						}else{
							tvContactLastName.setText("");
						}
							
						
					
				} catch (Exception e) {
					onError(e);
				}
			}
			
			@Override
			public void onError(Exception exception) {
              /*  Toast.makeText(MainActivity.this,
                               MainActivity.this.getString(SalesforceSDKManager.getInstance().getSalesforceR().stringGenericError(), exception.toString()),
                               Toast.LENGTH_LONG).show();*/
				EventsObservable.get().notifyEvent(EventType.RenditionComplete);
			}
		});
	
		
		
	} catch (Exception e) {
		Log.i("NCS","Exception  2 is  :"+e.getMessage());
	}

	
	}
	
	
	public void createAccount()
	{
		String objectType = "Account";
		HashMap<String, Object> fields = new HashMap<String, Object>();
		fields.put("Name",etAccountName.getText().toString());
		fields.put("AccountNumber",etAccountNumber.getText().toString());
		fields.put("AnnualRevenue",etAnnuaLRevenue.getText().toString());
		fields.put("Fax",etfax.getText().toString());
		fields.put("Phone",etPhone.getText().toString());
		fields.put("Website",etwebsite.getText().toString());
		fields.put("NumberOfEmployees",etEmployees.getText().toString());
		fields.put("Industry", mIndustry.getSelectedItem().toString());
		fields.put("Ownership", mOwnerShip.getSelectedItem().toString());
		fields.put("Type", mType.getSelectedItem().toString());
		fields.put("Rating", mRating.getSelectedItem().toString());
		fields.put("ParentId",parantAccountID);
		fields.put("BillingCity",etBilingCity.getText().toString());
		fields.put("BillingCountry",etBilingcountry.getText().toString());
		fields.put("BillingPostalCode",etBilingZip.getText().toString());
		fields.put("BillingState",etBilingState.getText().toString());
		fields.put("BillingStreet",etBilingStreet.getText().toString());
		fields.put("ShippingCity",etShippingcity.getText().toString());
		fields.put("ShippingCountry",etShippingCountry.getText().toString());
		fields.put("ShippingPostalCode",etShippingcode.getText().toString());
		fields.put("ShippingState",etshippingstate.getText().toString());
		fields.put("ShippingStreet",etShippingStreet.getText().toString());
		
		try {
		    RestRequest restRequest = RestRequest.getRequestForCreate(Bean_Class.api_Version,objectType,fields);
		    
		    Log.i("NCS","REquest is  :"+restRequest);
		    
		    client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {     
						Log.i("TPT","Response is   :"+result);
						
						JSONObject json = new JSONObject(result.toString());
						if(json!= null){
							Log.i("TPT","Response is   :"+json.getString("success"));
							if(json.getString("success").equalsIgnoreCase("true")){
								
								etAccountNumber.setText("");
								etAccountName.setText("");
								etAnnuaLRevenue.setText("");
								etBilingCity.setText("");
								etBilingcountry.setText("");
								etBilingState.setText("");
								etBilingStreet.setText("");
								etBilingZip.setText("");
								etEmployees.setText("");
								etfax.setText("");
								etParentAccount.setText("");
								etPhone .setText("");
								etShippingcity.setText("");
								etShippingcode.setText("");
								etShippingCountry.setText("");
								etshippingstate.setText("");
								etShippingStreet.setText("");
								etwebsite.setText("");
								mHomeItemListener.onCategoryClicked(-2);
							}
							
						}
					
						
						}                                
					catch (Exception e) {
						Log.i("TPT","Exception is   :"+e.getMessage());                      
					}
				}
				
				//@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});
		} 
		catch (Exception e) {
			Log.i("NCS","Exception is   :"+e.getMessage());
		    
		}

	}
	
	public void createContact(){
		{
			String objectType = "Contact";
			HashMap<String, Object> fields = new HashMap<String, Object>();
			
			fields.put("AccountId",parantAccountID);
			fields.put("FirstName",etFirstName.getText().toString());
			fields.put("LastName",etLastName.getText().toString());
			fields.put("Phone",etContactphone.getText().toString());
			fields.put("MailingCity",etMaillingCity.getText().toString());
			fields.put("MailingState",etMaillingstate.getText().toString());
			fields.put("MailingCountry", etMailingCountry.getText().toString());
			fields.put("MailingPostalCode", etMaillingZip.getText().toString());
			fields.put("MailingStreet", etMaillingStreet.getText().toString());
			fields.put("OtherCity", etOtherCity.getText().toString());
			fields.put("OtherCountry",etOtherCountry.getText().toString());
			fields.put("OtherPostalCode",etOtherZip.getText().toString());
			fields.put("OtherState",etOtherState.getText().toString());
			fields.put("OtherStreet",etOtherStreet.getText().toString());
			fields.put("Email",etEmail.getText().toString());
			fields.put("MobilePhone",etMobile.getText().toString());
			fields.put("Title",etTitle.getText().toString());
			fields.put("LeadSource", etLeadSource.getSelectedItem().toString());
			fields.put("Description", etDescription.getText().toString());
			
			try {
			    RestRequest restRequest = RestRequest.getRequestForCreate(Bean_Class.api_Version,objectType,fields);
			    
			    Log.i("NCS","REquest is  :"+restRequest);
			    
			    client.sendAsync(restRequest, new AsyncRequestCallback() {
					@Override
					public void onSuccess(RestRequest request, RestResponse result) {
						try {     
							Log.i("TPT","Response is   :"+result);
							
							JSONObject json = new JSONObject(result.toString());
							if(json!= null){
								Log.i("TPT","Response is   :"+json.getString("success"));
								if(json.getString("success").equalsIgnoreCase("true")){
									mHomeItemListener.onCategoryClicked(-2);
								}
								
							}
						
							
							}                                
						catch (Exception e) {
							Log.i("TPT","Exception is   :"+e.getMessage());                      
						}
					}
					
					//@Override
					public void onError(Exception exception) {
						EventsObservable.get().notifyEvent(EventType.RenditionComplete);
					}
				});
			} 
			catch (Exception e) {
				Log.i("NCS","Exception is   :"+e.getMessage());
			    
			}

		}
		
		
	}
	
	
	
	LookupAdapter adapter;
	public void accountLookupDetails(){
		
		
		
		 lookupDialog = new Dialog(getActivity());
		lookupDialog.setContentView(R.layout.accountlookup);
		lookupDialog.setTitle("FieldService360");
		lvLookup = (ListView) lookupDialog.findViewById(R.id.lvAccountlookuplistview);
		etLookup = (EditText) lookupDialog.findViewById(R.id.etFilteraccount);
		 adapter = new LookupAdapter(FragmentA.list);
		lvLookup.setAdapter(adapter);
		etLookup.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before, int count) {
           
            	adapter.getFilter().filter(s);
            	
            }
            public void beforeTextChanged(CharSequence s, int start, int count,
            		int after) {
            	
            }
            public void afterTextChanged(Editable s) {
            	
            }
            });
		
		lookupDialog.show();
			
		
		
		lvLookup.setOnItemClickListener(this);

		
	}
	
	class LookupAdapter extends BaseAdapter implements Filterable{

		private  ValueFilter valueFilter;
	
		ArrayList<Bean_Class> mStringFilterList = new ArrayList<Bean_Class>();
		public LookupAdapter(ArrayList<Bean_Class> list) {
			data = list;
			mStringFilterList = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return data.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

	  class ViewHolder{
			public TextView name,age;
		}
		
		@Override
		public View getView(int position, View v, ViewGroup parent) {
			ViewHolder holder;
			if(v== null){
				holder = new ViewHolder();
				LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflater.inflate(android.R.layout.simple_list_item_1, null);
				holder.name = (TextView) v.findViewById(android.R.id.text1);
				v.setTag(holder);
			}else{
				holder = (ViewHolder) v.getTag();
			}
			
			Bean_Class b = data.get(position);
			holder.name.setText(b.getName());
			
			
			return v;
		}
		
		
		 public Filter getFilter() {
	        	if(valueFilter==null) {

	        		valueFilter=new ValueFilter();
	        	}
	        	
	        	return valueFilter;
	        }
	        
	        private class ValueFilter extends Filter
	        {

	        	@Override
	        	protected FilterResults performFiltering(CharSequence constraint)
	        	{
	        		FilterResults results=new FilterResults();

	        			if(constraint!=null && constraint.length()>0){

	        				filterList=new ArrayList<Bean_Class>();

	        				for(int i=0;i<mStringFilterList.size();i++){

	        					String mLastName = mStringFilterList.get(i).getName();
	        					if(mLastName.toLowerCase().contains(constraint.toString()))
	        					{
	        						filterList.add(mStringFilterList.get(i));

	        					}
	        				}
	        				results.count=filterList.size();
	        				results.values=filterList;
	        				FragmentB.this.isFiltered = true;
	        			}else{
	        				FragmentB.this.isFiltered = false;
	        				results.count=mStringFilterList.size();
	        				results.values=mStringFilterList;

	        			}

	        			return results;
	        	}

	        	@SuppressWarnings("unchecked")
	        	@Override
	        	protected void publishResults(CharSequence constraint,
	        			FilterResults results) 
	        	{
	        		data = (ArrayList<Bean_Class>) results.values;

	        		notifyDataSetChanged();

	        	}

		
	        }
	}

		


	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btSave1:
			if (!flag) {
				createAccount();
			} else {
				Log.i("NCS", "Update id :" + parantAccountID);
				updateAccount(parantAccountID);
			}
			break;

		case R.id.btEdit:
			flag = true;
			llayout.setVisibility(View.GONE);
			svAccount.setVisibility(View.VISIBLE);
			editAcount();    
			break;
		case R.id.etParentAccount:
			accountLookupDetails();
			break;

		case R.id.btNewContact:
			
			svAccount.setVisibility(View.GONE);
			llayout.setVisibility(View.GONE);
			svContact.setVisibility(View.VISIBLE);
			
			etMailingCountry.setText(bean.getBillingCountry());
			etMaillingCity.setText(bean.getBillingCity());
			etMaillingstate.setText(bean.getBillingState());
			etMaillingStreet.setText(bean.getBillingStreet());
			etMaillingZip.setText(bean.getBillingPostalCode());
			
			etContactphone.setText(bean.getPhno());
			etContactAccountName.setText(bean.getName());
			parantAccountID = bean.getId();
			Log.i("NCS","Id is :"+parantAccountID);
			
			break;
			
		case R.id.btSave2:
			createContact();
			break;
			
		case R.id.tvContactBillingToShipping:
			String MaillingCity = etMaillingCity.getText().toString();
			if (MaillingCity != null) {
				etOtherCity.setText(MaillingCity);
			}
			String MailingCountry = etMailingCountry.getText().toString();
			if (MailingCountry != null) {
				etOtherCountry.setText(MailingCountry);
			}

			String MailingZip = etMaillingZip.getText().toString();
			if (MailingZip != null) {
				etOtherZip.setText(MailingZip);
			}
			String MailingState = etMaillingstate.getText().toString();
			if (MailingState != null) {
				etOtherState.setText(MailingState);
			}
			String MailingStreet = etMaillingStreet.getText().toString();
			if (MailingStreet != null) {
				etOtherStreet.setText(MailingStreet);
			}
			
		case R.id.tvBillingToShipping:
			
			String billingCity = etBilingCity.getText().toString();
			if (billingCity != null) {
				etShippingcity.setText(billingCity);
			}
			String billingCountry = etBilingcountry.getText().toString();
			if (billingCountry != null) {
				etShippingCountry.setText(billingCountry);
			}

			String billingZip = etBilingZip.getText().toString();
			if (billingZip != null) {
				etShippingcode.setText(billingZip);
			}
			String billingState = etBilingState.getText().toString();
			if (billingState != null) {
				etshippingstate.setText(billingState);
			}
			String billingStreet = etBilingStreet.getText().toString();
			if (billingStreet != null) {
				etShippingStreet.setText(billingStreet);
			}
			break;
		default:
			break;
		}
	}


	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {

		Bean_Class bean  = data.get(arg2);
		Log.i("NCS","Name  :"+bean.getName());
		etParentAccount.setText(bean.getName());
		parantAccountID = bean.getId();
		lookupDialog.dismiss();
	}
}              
